package com.example.videoserver.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.file.FileWriter;
import com.example.videoserver.config.WebConfig;
import com.example.videoserver.utli.ResponseRest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
public class FileUploadController {

//    @Value("${upload.path}")
    public static String uploadPath = "/config/file/"; // 在application.yml里定义上传文件的最终保存路径

    @PostMapping("/upload")
    public Object handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "Failed to upload because the file is empty";
        }

        if (!FileUtil.exist(uploadPath)) {
            FileUtil.mkParentDirs (uploadPath);
        }

        try {
            // 获取文件原名
            String originalFilename = file.getOriginalFilename();
            // 文件保存路径
            Path destinationFilePath = Paths.get(uploadPath, originalFilename);
            // 将文件保存到指定路径
            Files.copy(file.getInputStream(), destinationFilePath);
            
            return ResponseRest.success("/static/" + originalFilename);
        } catch (IOException e) {
            throw new RuntimeException("Failed to store file " + file.getOriginalFilename(), e);
        }
    }
}